import React, { useState } from 'react'
import './index.less'

export interface BoxGroupBox {
  key: string
  content: React.ReactNode
  collapsedLabel?: React.ReactNode
  className?: string
}

export interface BoxGroupProps {
  boxes: BoxGroupBox[]
  defaultActiveKey?: string
  activeKey?: string
  onChange?: (key: string) => void
  className?: string
  style?: React.CSSProperties
}

const BoxGroup: React.FC<BoxGroupProps> = ({
  boxes,
  defaultActiveKey,
  activeKey: controlledActiveKey,
  onChange,
  className,
  style,
}) => {
  const [uncontrolledActiveKey, setUncontrolledActiveKey] = useState(defaultActiveKey || boxes[0]?.key || '')
  const isControlled = controlledActiveKey !== undefined
  const activeKey = isControlled ? controlledActiveKey : uncontrolledActiveKey

  const handleBoxClick = (key: string) => {
    if (key === activeKey) return
    if (!isControlled) setUncontrolledActiveKey(key)
    onChange?.(key)
  }

  return (
    <div className={['custom-boxgroup-container', className].filter(Boolean).join(' ')} style={style}>
      {boxes.map((box) => {
        const isActive = box.key === activeKey
        return (
          <div
            key={box.key}
            className={['boxgroup-box', box.className, isActive ? 'boxgroup-active' : 'boxgroup-inactive']
              .filter(Boolean)
              .join(' ')}
            onClick={() => handleBoxClick(box.key)}
          >
            <div className="boxgroup-content" style={{ display: isActive ? 'flex' : 'none' }}>
              {box.content}
            </div>
            {!isActive && <div className="boxgroup-collapsedLabel">{box.collapsedLabel}</div>}
          </div>
        )
      })}
    </div>
  )
}

export default BoxGroup
